// pages/sjwppublish/sjwppublish.js
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    userInfo: '',
    inputShow: '',
    formlist: [
      // { isrequire: false, value: '', label: '物品类别', valueType: 'text', key: 'type', tips: '请选择', type: 'select', data: [] },
      { isrequire: true, value: '', label: '物品名称', valueType: 'text', key: 'thingName', tips: '请填写', type: 'input'},
      { isrequire: false, value: '', label: '商品型号', valueType: 'text', key: 'property', tips: '如果有多种型号，请以-分隔', type: 'input'},
      { isrequire: true, value: '', label: '库存', valueType: 'number', key: 'thingNumber', tips: '请填写', type: 'input' },
      {label: '价格', type: 'label'},
      { isrequire: true, value: '', label: '商品价格', valueType: 'digit', key: 'price', tips: '￥0', type: 'input' },
      { isrequire: true, value: '', label: '运费', valueType: 'digit', key: 'thingFare', tips: '￥0', type: 'input' }
    ],  
    showName: '', 
    formData: {
      shopId:'',
      price:'',	
      thingNumber:'',		 //库存
      thingName:'',	
      thingShowImg: '',
      thingBanerImg: '',
      thingProductsText: '',
      property:'',
      thingFare:'',				
      userId:'',
      // type:'',
      thingProductsImg:''
    },
    keys: '',
    thingShowImg: [],
    thingBanerImg: [],
    thingProductsImg: [],  
    items: [
      { name: '1', value: '1年 费用365元', checked: true },
      { name: '2', value: '2年 费用500元' },
      { name: '3', value: '免费试用15天' }
    ],
    canSubmit:false,
    isTip: false
  },
  publish: function (e) {
    this.data.formData.price = this.data.formData.price.split("￥")[1];
    this.data.formData.thingFare = this.data.formData.thingFare.split("￥")[1];
    var _this = this;
    if (_this.data.canSubmit) {
      wx.request({
        url: app.globalData.httpApiCar + 'shopThing/save',
        method: 'POST',
        data: this.data.formData,
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          if(res.data.success){
            wx.redirectTo({
              url: '/pages/shopIndex/shopIndex?id=' + wx.getStorageSync('ShopId'),
            })
          }
          else{
            wx.showModal({
              title: '提示',
              content: res.data.error,
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  wx.navigateBack()
                }
              }
            })
          }
        }
      })
    }
  },
  radioChange: function (e) {
  },
  bindInputFunc: function (e) {
    let key = e.currentTarget.dataset.key;
    let item = e.currentTarget.dataset.item;
    if (item.label == '商品价格' || item.label == '运费') {
      if (e.detail.value.indexOf("￥") >= 0) {
        e.detail.value = e.detail.value.split("￥")[1];
      }
      
      this.data.formData[key] = '￥' + e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
    }
    else{
      this.data.formData[key] = e.detail.value;
    }
    this.setData({ formData: this.data.formData });
    this.changeValue();
  },
  // 添加图片
  addPhoto: function (e) {
    var that = this,
      count = 0,
      key = e.currentTarget.dataset.id,
      only = e.currentTarget.dataset.only;
    only ? count = 1 : count = 9 - this.data[key].length;
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 0)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /*上传图片*/
  uploadImg: function (path, key, tag, oIndex) {
    var data1 = app.uploadimg({
      url: app.globalData.httpApiCar + 'uploadfile/upload1',
      path: path,
      globalkey: this,
      realpath: this.data[key],
      showkey: key,
      key: 'formData.' + key,
      tag: tag,
      oIndex: oIndex
    });
  },
  // 修改图片
  changePhoto: function (e) {
    var that = this,
      key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 1, index)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  delImg: function (e) {
    var key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    this.data[key].splice(index, 1);
    this.setData({
      [key]: this.data[key],
      ['formData.' + key]: this.data[key].join(",")
    });
    this.changeValue();

  },
  changeValue: function () {
    var flag = true;
    var item = this.data.formData;
    if ((item.price == '') || (item.thingNumber == '') || (item.thingName == '') || (item.thingFare == '') || (item.thingShowImg == '') || (item.thingProductsImg == '') || (item.thingBanerImg == '') || (item.thingProductsText == '')) {
      flag = false;
    }
    this.setData({
      canSubmit: flag
    })
  },
  //输入框点击事件
  inputTap(e) {
    var item = e.currentTarget.dataset.item;
    this.data.inputShow = true;
    this.data.value = this.data.formData[item.key];
    if (this.data.formData[item.key] == '' && item.isrequire) {
      this.data.active = '';
    } else {
      this.data.active = 'active';
    }
    wx.setNavigationBarTitle({
      title: item.label
    })
    if(item.label == '商品型号'){
      this.setData({
        isTip: true
      })
    }
    else{
      this.setData({
        isTip: false
      })
    }
    this.setData({
      inputShow: this.data.inputShow,
      value: this.data.value,
      currentInput: item,
      active: this.data.active
    })
    this.changeValue()
  },
  bindFormSubmit: function (e) {
    var item = this.data.currentInput;
    var flag = true;
    if (this.data.active != '') {
      if (item.reg) {
        var reg = new RegExp(item.reg);
        // var reg = item.reg;
        if (!reg.test(e.detail.value.con)) {
          flag = false;
          this.setData({
            'modelData.showModal': true,
            'modelData.content': '请输入正确的' + item.label
          })
        }
      }
      if (flag) {
        this.data.inputShow = false;
        this.data.formData[item.key] = e.detail.value.con;
        wx.setNavigationBarTitle({
          title: '商品发布'
        })
        this.setData({
          inputShow: this.data.inputShow,
          value: '',
          formData: this.data.formData
        })
        this.changeValue()
      }
    }
  },
  bindPickerChange: function (e) {
    var arr = [];
    arr = this.data.formlist;
    var item=e.currentTarget.dataset.item;
    this.data.formData.type = item.data[e.detail.value].id;
    this.setData({
      showName: item.data[e.detail.value].title,
      formData: this.data.formData
    })
    this.changeValue()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var key1 = 'formData.userId';
    var key2 = 'formData.shopId';
    this.setData({
      [key1]: JSON.parse(wx.getStorageSync('userInfo')).id,
      [key2]: wx.getStorageSync('ShopId'),
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
    var that = this;
    
    //wx.clearStorage();
  },
  bindobj: function (oldval, newval, key, index) {
    var arr = [];
    arr = this.data[oldval];
    arr[index][key] = newval;
    this.setData({
      formlist: arr
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //wx.clearStorage();
    var arr = [{ id: 1, icon: app.globalData.imageUrl + 'ic_gastronomy@2x.png', title: '美食', url: '/pages/hotSeach/hotSeach' },
    { id: 2, icon: app.globalData.imageUrl + 'ic_hotel@2x.png', title: '酒店', url: '/pages/hotSeach/hotSeach' },
    { id: 3, icon: app.globalData.imageUrl + 'ic_fallow@2x.png', title: '休闲娱乐', url: '/pages/hotSeach/hotSeach' },
    { id: 4, icon: app.globalData.imageUrl + 'ic_lido@2x.png', title: '丽人美发', url: '/pages/hotSeach/hotSeach' },
    { id: 5, icon: app.globalData.imageUrl + 'ic_pet@2x.png', title: '宠物', url: '/pages/hotSeach/hotSeach' },
    { id: 6, icon: app.globalData.imageUrl + 'ic_maternal_and_infant@2x.png', title: '母婴', url: '/pages/hotSeach/hotSeach' },
    { id: 7, icon: app.globalData.imageUrl + 'ic_wedding_photography@2x.png', title: '结婚摄影', url: '/pages/hotSeach/hotSeach' },
    { id: 8, icon: app.globalData.imageUrl + 'ic_sports@2x.png', title: '运动健身', url: '/pages/hotSeach/hotSeach' },
    { id: 9, icon: app.globalData.imageUrl + 'ic_auto_service@2x.png', title: '汽车服务', url: '/pages/hotSeach/hotSeach' },
    { id: 10, icon: app.globalData.imageUrl + 'ic_domestic_outfit_building_materials@2x.png', title: '家装建材', url: '/pages/hotSeach/hotSeach' },
    { id: 11, icon: app.globalData.imageUrl + 'ic_education_and_training@2x.png', title: '教育培训', url: '/pages/hotSeach/hotSeach' },
    { id: 12, icon: app.globalData.imageUrl + 'ic_costume@2x.png', title: '服装鞋帽', url: '/pages/hotSeach/hotSeach' },
    { id: 13, icon: app.globalData.imageUrl + 'ic_freight_moving@2x.png', title: '货运搬家', url: '/pages/hotSeach/hotSeach' },
    { id: 14, icon: app.globalData.imageUrl + 'ic_homemaking@2x.png', title: '家政', url: '/pages/hotSeach/hotSeach' },
    { id: 15, icon: app.globalData.imageUrl + 'ic_Industry_resources@2x.png', title: '更多', url: '/pages/hotSeach/hotSeach' }];
    this.bindobj('formlist', arr, 'data', 0);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})